import { create } from 'zustand';
import { Dish } from '@/types/dish';

interface CartItem {
  dish: Dish;
  quantity: number;
}

interface CartState {
  items: CartItem[];
}

interface CartActions {
  addItem: (dish: Dish) => void;
  removeItem: (dishId: string) => void;
  updateQuantity: (dishId: string, quantity: number) => void;
  clearCart: () => void;
  getTotalPrice: () => number;
  getTotalItems: () => number;
}

type CartStore = CartState & CartActions;

// 创建一个选择器类型
type CartSelector<T> = (state: CartStore) => T;

// 修改 create 的类型定义，添加选择器支持
export const useCartStore = create<CartStore>((set, get) => ({
  items: [],
  
  addItem: (dish: Dish) => {
    set((state: CartState) => {
      const existingItem = state.items.find((item: CartItem) => item.dish.id === dish.id);
      
      if (existingItem) {
        return {
          items: state.items.map((item: CartItem) =>
            item.dish.id === dish.id
              ? { ...item, quantity: item.quantity + 1 }
              : item
          ),
        };
      }
      
      return {
        items: [...state.items, { dish, quantity: 1 }],
      };
    });
  },
  
  removeItem: (dishId: string) => {
    set((state: CartState) => ({
      items: state.items.filter((item: CartItem) => item.dish.id !== dishId),
    }));
  },
  
  updateQuantity: (dishId: string, quantity: number) => {
    set((state: CartState) => ({
      items: state.items.map((item: CartItem) =>
        item.dish.id === dishId
          ? { ...item, quantity: Math.max(0, quantity) }
          : item
      ).filter((item: CartItem) => item.quantity > 0),
    }));
  },
  
  clearCart: () => {
    set({ items: [] });
  },
  
  getTotalPrice: () => {
    const { items } = get();
    return items.reduce((total: number, item: CartItem) => 
      total + item.dish.price * item.quantity, 0);
  },
  
  getTotalItems: () => {
    const { items } = get();
    return items.reduce((total: number, item: CartItem) => 
      total + item.quantity, 0);
  },
}));

// 导出选择器类型
export type { CartSelector }; 